package com.service.impl;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.dao.SysDeptDao;
import com.domain.Node;
import com.domain.sys.SysDept;
import com.exception.ServiceException;
import com.service.SysDeptService;
import com.util.MyValid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;



@Service
public class SysDeptServiceImpl implements SysDeptService {
	@Autowired
	private SysDeptDao sysDeptDao;
	@Override
	public ArrayList<Map<String, Object>> findObjects() {
		ArrayList<Map<String, Object>> list=
		sysDeptDao.findObjects();
		MyValid.isService(list==null||list.size()==0,"没有部门信息");
		return list;
	}
	@Override
	public ArrayList<Node> findZTreeNodes() {
		ArrayList<Node> list=
		sysDeptDao.findZTreeNodes();

		MyValid.isService(list==null||list.size()==0,"没有部门信息");

		return list;
	}
	@Override
	public Integer updateObject(SysDept entity) {
		//1.合法验证
		MyValid.isService(entity==null,"保存对象不能为空");

		MyValid.isService(StringUtils.isEmpty(entity.getName()),"部门不能为空");

		Integer rows;
		//2.更新数据
		try{
		rows=sysDeptDao.updateObject(entity);
		}catch(Exception e){
		e.printStackTrace();
		throw new ServiceException("更新失败");
		}
		//3.返回数据
		return rows;
	}
	
	@Override
	public Integer saveObject(SysDept entity) {
		//1.合法验证
		MyValid.isService(entity==null,"保存对象不能为空");

		MyValid.isService(StringUtils.isEmpty(entity.getName()),"部门不能为空");

		//2.保存数据
		Integer rows=sysDeptDao.insertObject(entity);
		//if(rows==1)
		//throw new ServiceException("save error");
		//3.返回数据
		return rows;
	}
	@Override
	public Integer deleteObject(Integer id) {
		//1.合法性验证

		MyValid.isService(id==null||id<=0,"数据不合法,id="+id);

		//2.执行删除操作
		//2.1判定此id对应的菜单是否有子元素
		Integer childCount=sysDeptDao.getChildCount(id);

		MyValid.isService(childCount>0,"此元素有子元素，不允许删除");

		//2.2判定此部门是否有用户
		//int userCount=sysUserDao.getUserCountByDeptId(id);
		//if(userCount>0)
		//throw new ServiceException("此部门有员工，不允许对部门进行删除");
		//2.2判定此部门是否已经被用户使用,假如有则拒绝删除
		//2.3执行删除操作
		Integer rows=sysDeptDao.deleteObject(id);

		MyValid.isService(rows==0,"此信息可能已经不存在");

		return rows;
	}


}
